package com.xtravel.common.helper;

import android.content.Context;
import android.content.SharedPreferences;
import org.apache.commons.lang3.StringUtils;

/**
 * @author kuner
 *
 * SharedPreferences 操作.
 *
 * 15-9-1.
 */
public class Preference {

    private Context context;

    private static final String FILE_NAME = "xtravel";

    public Preference(Context context){
        this.context = context;
    }

    /**
     * 添加.
     *
     * @param key   Key.
     * @param value Value.
     */
    public void setString(String key, String value) {
        SharedPreferences preference = getDefaultSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.remove(key);
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * 自增.
     */
    public long incr(String key) {
        if (StringUtils.isNotBlank(key)) {
            long l = getLong(key) + 1;
            setLong(key, l);
            return l;
        }
        return 0;
    }

    /**
     * 递减.
     */
    public long decr(String key) {
        if (StringUtils.isNotBlank(key)) {
            long tmp = getLong(key);
            long l = tmp > 0 ? tmp - 1 : 0;
            setLong(key, l);
            return l;
        }
        return 0;
    }

    /**
     * 添加.
     *
     * @param key   Key.
     * @param value Value.
     */
    public void setLong(String key, long value) {
        SharedPreferences preference = getDefaultSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.remove(key);
        editor.putLong(key, value);
        editor.commit();
    }

    /**
     * 添加.
     *
     * @param key   Key.
     * @param value Value.
     */
    public void setInt(String key, int value) {
        setLong(key, value);
    }

    /**
     * Get.
     *
     * @param key Key.
     *
     * @return Value
     */
    public String getString(String key) {
        SharedPreferences preference = getDefaultSharedPreferences();
        return preference.getString(key, "");
    }

    /**
     * Get.
     *
     * @param key Key.
     *
     * @return Value
     */
    public long getLong(String key) {
        SharedPreferences preference = getDefaultSharedPreferences();
        return preference.getLong(key, 0);
    }

    /**
     * Get.
     *
     * @param key Key.
     *
     * @return value
     */
    public int getInt(String key) {
        return (int) getLong(key);
    }

    /**
     * 获取默认SharedPreferences.
     *
     * @return 默认SharedPreferences
     */
    private SharedPreferences getDefaultSharedPreferences() {
        return context.getSharedPreferences(FILE_NAME, Context.MODE_APPEND);
    }

}
